// sse.js
import {
	EventSourcePolyfill
} from 'event-source-polyfill';

export default {
	install(VueOrApp) {
		const sseFunction = (url, onMessage, onError, headers = {}) => {
			if (!('EventSource' in window)) {
				console.error('SSE is not supported in this environment.');
				if (onError) onError(new Error('SSE is not supported'));
				return null;
			}

			const eventSource = new EventSourcePolyfill(url, {
				headers: headers
			});

			eventSource.onmessage = (event) => {
				let data;
				try {
					data = JSON.parse(event.data);
					onMessage(data);
				} catch (e) {
					console.error('Failed to parse message:', e);
					if (onError) onError(e);
				}
			};

			eventSource.onerror = (error) => {
				console.error('EventSource failed:', error);
				if (onError) onError(error);
				eventSource.close();
			};

			return eventSource;
		};

		if (VueOrApp.prototype) {
			VueOrApp.prototype.$sse = sseFunction;
		} else if (VueOrApp.config && VueOrApp.config.globalProperties) {
			VueOrApp.config.globalProperties.$sse = sseFunction;
		}
	}
};